const userModel = require('../models/userModel')
const jwt = require('jsonwebtoken')
const { JWT_SECRET_KEY } = require('../project.config')

class authController {
    static async register (ctx) {
        const { account, password, inviteCode } = ctx.request.body || {}
        if (account === '' || password === '' || inviteCode) {
            ctx.body = {
                code: 0,
                msg: '字段不能为空',
                data: null,
            }
            return
        }

        // const temp = await InviteCode.findOne({
        //     code: inviteCode,
        // }).exec()
        // if (!temp || temp.userID) {
        //     ctx.body = {
        //         code: 0,
        //         msg: '邀请码不正确',
        //         data: null,
        //     }
        // }
        const one = await userModel.findOne({
            account,
        }).exec()
        if (one) {
            ctx.body = {
                code: 0,
                data: null,
                msg: '该用户已存在',
            }
            return
        }
        const user = new userModel({
            account,
            password,
        })

        const res = await user.save()
        // temp.userID = res._id
        // temp.meta.updateAt = new Date().getTime()
        // await temp.save()

        ctx.body = {
            code: 1,
            msg: '注册成功',
            data: res,
        }
    }

    static async login (ctx) {
        const { account, password } = ctx.request.body
        if (account === '' || password === '') {
            ctx.body = {
                code: 0,
                msg: '字段不能为空',
                data: null,
            }
            return
        }
        const temp = await userModel.findOne({
            account,
        }).exec()
        if (!temp) {
            ctx.body = {
                code: 0,
                msg: '用户名或密码错误',
                data: null,
            }
            return
        }
        const user = {
            account: temp.account,
            roleId: temp.roleId,
            id: temp._id,
        }

        if (temp.password === password) {
            ctx.body = {
                code: 1,
                msg: '登入成功',
                data: {
                    user,
                    token: jwt.sign(user, JWT_SECRET_KEY),
                },
            }
            return
        }
        //当密码错误时，执行以下操作
        ctx.body = {
            code: 0,
            msg: '用户名或密码错误',
            data: null,
        }
    }

    // static async createInviteCode(ctx) {
    //     const code = new InviteCode({
    //         code: uuidv4(),
    //         user: '',
    //     })
    //     const data = await code.save()
    //     ctx.body = {
    //         code: 1,
    //         data,
    //         msg: '创建成功',
    //     }
    // }
}

module.exports = authController
